<template>
  <el-cascader
    v-model="formData[data.field]"
    :options="data.options"
    filterable
    clearable
    :disabled="data.disabled"
    :props="props"
    collapse-tags
    :placeholder="data.placeholder ? data.placeholder : '请选择'"
    size="default"
    @change="searchFun"
  >
  </el-cascader>
</template>

<script lang="ts">
import { defineComponent, computed, watch, reactive, toRefs } from 'vue'
import { baseForm } from '@/common/mixins/index'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'BaseCascader',
  props: {
    form: {
      type: Object,
      default: () => ({})
    },
    data: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['onSearchFun', 'update:form'],
  setup(props, { emit }) {
    const formData: any = computed({
      get: () => props.form,
      set: (val) => emit('update:form', val)
    })

    const state = reactive({
      props: {
        multiple: !props.data.fillLevel && props.data.multiple,
        checkStrictly:
          props.data.defaultProps && props.data.defaultProps.checkStrictly
            ? props.data.defaultProps.checkStrictly
            : !props.data.fillLevel,
        label: props.data.defaultProps && props.data.defaultProps.label ? props.data.defaultProps.label : 'value',
        value: props.data.defaultProps && props.data.defaultProps.value ? props.data.defaultProps.value : 'key'
      }
    })

    watch(
      () => props.form.serviceLabel,
      (newVal: any, oldVal: any) => {
        if (newVal && newVal.length > 5) {
          ElMessage.error('最多只支持选择5项')
          props.form.serviceLabel = oldVal.slice(0, 5)
        }
      }
    )

    const searchFun = () => {
      baseForm.searchFun(emit)
    }
    return { searchFun, formData, ...toRefs(state) }
  }
})
</script>

<style lang="stylus">
// 级联标签的最大宽度
.el-cascader__tags
  .el-tag__content
    max-width 120px
    overflow hidden
    text-overflow ellipsis
    white-space nowrap
// 级联下拉选项每级的最大宽度
.el-cascader-node__label
  max-width 180px
</style>
